import { Service } from 'egg';
import { getCurrentStimp, deleteNullOrUndefinedField } from '../utils';


export default class BaseService extends Service {
    public model: any;
    constructor(ctx) {
        super(ctx);
    }
    async index(page = 1, pageSize = 20, query) {
        // 查询未删除的字段
        query.is_delete = 0;
        const queryParams = {
            where: deleteNullOrUndefinedField(query),
            order: [['id', 'DESC']],
        };
        if (Object.keys(query).length === 0) {
            Object.assign(queryParams, {
                offset: (Number(page) - 1) * pageSize,
                limit: pageSize,
            });
        }
        const result: any = await this.model
            .findAndCountAll(queryParams);
        return {
            list: result.rows,
            total: result.count,
            page,
            pageSize,
        }
    };

    async create(data) {
        const result = await this.model.create(data);
        return result;
    }

    async bulkCreate(data) {
        const result = await this.model.bulkCreate(data);
        return result;
    }

    async detail(id) {
        const result = await this.model.findOne({
            where: { id }
        });
        return result;
    }

    async update(id, data) {
        const update_at = getCurrentStimp();
        Object.assign(data, { update_at });
        try {
            return await this.model
                .update(
                    data,
                    {
                        where: {
                            id
                        }
                    }
                )
        } catch (err: any) {
            this.ctx.logger.error(err.message);
            return '';
        }
    }

    // 软删除
    async delete(id) {
        const update_at = getCurrentStimp();
        try {
            return await this.model
                .update(
                    { is_delete: 1, data: update_at },
                    {
                        where: {
                            id
                        }
                    }
                )
        } catch (err: any) {
            this.ctx.logger.error(err.message);
            return '';
        }
    }

    async destroy(id) {
        const result = await this.model.destroy({ where: { id } });
        return result;
    }

    async findAll(where, attributes) {
        const params = {
            limit: 20,
            where,
        }

        if (attributes) {
            Object.assign(params, { attributes });
        }

        const result = await this.model.findAll(params);
        return result;
    }

}
